package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.ContactFormMapper;
import com.example.model.dto.ContactFormDTO;
import com.example.model.entity.ContactForm;
import com.example.service.ContactFormService;
import com.example.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 联系表单服务实现类
 */
@Service
public class ContactFormServiceImpl extends ServiceImpl<ContactFormMapper, ContactForm> implements ContactFormService {
    
    private static final Logger logger = LoggerFactory.getLogger(ContactFormServiceImpl.class);
    
    private final EmailService emailService;
    
    public ContactFormServiceImpl(EmailService emailService) {
        this.emailService = emailService;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ContactForm submitContactForm(ContactFormDTO formDTO) {
        logger.info("开始处理联系表单提交: {}", formDTO);
        
        try {
            ContactForm contactForm = new ContactForm();
            BeanUtils.copyProperties(formDTO, contactForm);
            
            // 设置初始状态和时间
            contactForm.setStatus(0); // 0: 未处理
            LocalDateTime now = LocalDateTime.now();
            contactForm.setCreatedAt(now);
            contactForm.setUpdatedAt(now);
            
            // 保存表单
            boolean saved = save(contactForm);
            
            if (!saved) {
                logger.error("保存联系表单失败");
                throw new RuntimeException("保存联系表单失败");
            }
            
            logger.info("联系表单保存成功: id={}", contactForm.getId());
            
            // 发送邮件通知
            try {
                boolean emailSent = emailService.sendContactFormNotification(contactForm);
                if (!emailSent) {
                    logger.warn("发送联系表单通知邮件失败，但表单已保存成功");
                }
            } catch (Exception e) {
                // 邮件发送失败不影响表单提交的结果
                logger.error("发送邮件通知时发生异常: ", e);
            }
            
            return contactForm;
        } catch (Exception e) {
            logger.error("提交联系表单时发生异常: ", e);
            throw new RuntimeException("提交联系表单时发生异常: " + e.getMessage(), e);
        }
    }
} 